package lesson.thread.test9;

public class Ticket implements Runnable{
    private int ticket = 1000;

    @Override
    public void run() {
        while (true){
            if("窗口一".equals(Thread.currentThread().getName())){
                boolean result = synchronizedMethod();
                if (result) {
                    break;
                }
            }

            if("窗口二".equals(Thread.currentThread().getName())){
                synchronized (Ticket.class){
                    if(ticket == 0){
                        break;
                    }else {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticket--;
                        System.out.println(Thread.currentThread().getName()+"在卖票，还剩下"+ticket+"张票");
                    }
                }
            }

        }
    }

    private boolean synchronizedMethod() {
        if(ticket == 0){
            return true;
        }else {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticket --;
            System.out.println(Thread.currentThread().getName()+"在卖票，还剩下"+ticket+"张票");
        }
        return false;
    }
}
